package com.bupt.secret.test;

import java.security.*;
import java.util.Base64;

public class DataSigningExample {
    public static void main(String[] args) throws Exception {
        // 原始数据
        String data = "Sensitive data";

        // 创建密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();

        // 对数据进行哈希
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hash = md.digest(data.getBytes());
        System.out.println("hash:"+Base64.getEncoder().encodeToString(hash));

        // 对哈希值进行签名
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(hash);
        byte[] digitalSignature = signature.sign();

        // 输出签名
        System.out.println("Signature: " + Base64.getEncoder().encodeToString(digitalSignature));

        // 验证签名
        signature.initVerify(publicKey);
        signature.update(hash);
        boolean isValid = signature.verify(digitalSignature);
        System.out.println("Is signature valid? " + isValid);
    }
}